<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>试剂使用列表</title>
    <!-- Bootstrap 5 CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="css/bootstrap-icons.css" rel="stylesheet">
    <!-- 自定义样式 -->
    <link rel="stylesheet" href="css/style.css">
    <style>
        /* 多选下拉框样式 */
        .multi-select-container {
            position: relative;
        }
        
        .multi-select-input {
            min-height: 38px;
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
            padding: 6px 12px;
            background-color: #fff;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .multi-select-input:hover {
            border-color: #86b7fe;
        }
        
        .multi-select-input.active {
            border-color: #86b7fe;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }
        
        .selected-items {
            flex: 1;
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
            min-height: 24px;
            align-items: center;
        }
        
        .selected-item {
            background-color: #0d6efd;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.875rem;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        
        .selected-item .remove-btn {
            cursor: pointer;
            font-weight: bold;
            margin-left: 4px;
        }
        
        .selected-item .remove-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .placeholder {
            color: #6c757d;
            font-style: italic;
            background-color:#00000000
        }
        
        .dropdown-arrow {
            margin-left: 8px;
            transition: transform 0.2s;
        }
        
        .dropdown-arrow.rotated {
            transform: rotate(180deg);
        }
        
        .multi-select-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 1000;
            background: white;
            border: 1px solid #ced4da;
            border-top: none;
            border-radius: 0 0 0.375rem 0.375rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            max-height: 250px;
        }
        
        .search-box {
            padding: 8px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .options-container {
            max-height: 200px;
            overflow-y: auto;
        }
        
        .option-item {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #f8f9fa;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .option-item:hover {
            background-color: #f8f9fa;
        }
        
        .option-item.selected {
            background-color: #e3f2fd;
            color: #1976d2;
        }
        
        .option-item input[type="checkbox"] {
            margin: 0;
        }
        
        .no-options {
            padding: 16px;
            text-align: center;
            color: #6c757d;
            font-style: italic;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark navbar-custom">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">实验室管理系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="page1.html">试剂列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="page2.html">试剂使用列表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="page3.html">实验室预警信息看板</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="page4.html">试剂到期预警</a>
                    </li>
                </ul>
                <!-- 用户信息和退出登录 -->
                <div class="dropdown">
                    <a class="nav-link dropdown-toggle text-white" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-person-circle me-1"></i>
                        <span id="currentUserName">加载中...</span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                        <li><a class="dropdown-item" href="#" id="logoutBtn"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container-fluid">
        <div class="main-content">
            <!-- 页面标题 -->
            <div class="page-header">
                <h3 class="page-title">试剂使用列表</h3>
            </div>

            <!-- 搜索区域 - 暂时注释 -->
            <!--
            <div class="search-section">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label for="searchTime" class="form-label">使用时间</label>
                        <input type="date" class="form-control" id="searchTime">
                    </div>
                    <div class="col-md-3">
                        <label for="searchExperimentId" class="form-label">实验号</label>
                        <input type="text" class="form-control" id="searchExperimentId" placeholder="输入实验号">
                    </div>
                    <div class="col-md-3">
                        <label for="searchGroups" class="form-label">分组</label>
                        <input type="text" class="form-control" id="searchGroups" placeholder="输入分组名称">
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="button" class="btn btn-outline-primary search-btn" onclick="searchData()">
                            搜索
                        </button>
                    </div>
                </div>
            </div>
            -->

            <!-- 操作按钮 -->
            <div class="action-buttons">
                <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
                    新增
                </button>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#importModal">
                    导入
                </button>
            </div>

            <!-- 数据表格 -->
            <div class="table-container">
                <table class="table table-hover data-table">
                    <thead>
                        <tr>
                            <th style="width: 80px;">序号</th>
                            <th style="width: 150px;">时间</th>
                            <th style="width: 150px;">实验号</th>
                            <th style="width: 200px;">分组</th>
                            <th>详细项目</th>
                            <th style="width: 120px;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="dataTableBody">
                        <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="pagination-info">
                        <span id="paginationInfo">显示 0-0 条，共 0 条记录</span>
                    </div>
                    <nav aria-label="分页导航">
                        <ul class="pagination pagination-sm mb-0" id="pagination">
                            <!-- 分页按钮将通过JavaScript动态生成 -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增模态框 -->
    <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addModalLabel"><i class="bi bi-plus-circle me-2"></i>新增使用记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body2">
                    <form id="addForm">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="addTime" class="form-label">使用时间</label>
                                <input type="datetime-local" class="form-control" id="addTime" required>
                            </div>
                            <div class="col-md-6">
                                <label for="addExperimentId" class="form-label">实验号</label>
                                <input type="text" class="form-control" id="addExperimentId" required>
                            </div>
                            <div class="col-12">
                                <label for="addGroups" class="form-label">分组</label>
                                <div class="row" id="addGroups">
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="乳腺" id="addGroup1">
                                            <label class="form-check-label" for="addGroup1">乳腺</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="前列腺" id="addGroup2">
                                            <label class="form-check-label" for="addGroup2">前列腺</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="宫颈" id="addGroup3">
                                            <label class="form-check-label" for="addGroup3">宫颈</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="宫内膜" id="addGroup4">
                                            <label class="form-check-label" for="addGroup4">宫内膜</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="神经内分" id="addGroup5">
                                            <label class="form-check-label" for="addGroup5">神经内分</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="甲状腺" id="addGroup6">
                                            <label class="form-check-label" for="addGroup6">甲状腺</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="细胞蜡块" id="addGroup7">
                                            <label class="form-check-label" for="addGroup7">细胞蜡块</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <label for="addDetails" class="form-label">详细项目</label>
                                <div class="multi-select-container">
                                    <div class="multi-select-input" id="addDetailsInput">
                                        <div class="selected-items" id="addSelectedItems">
                                            <span class="placeholder">请选择详细项目...</span>
                                        </div>
                                        <div class="dropdown-arrow">
                                            <i class="bi bi-chevron-down"></i>
                                        </div>
                                    </div>
                                    <div class="multi-select-dropdown" id="addDetailsDropdown" style="display: none;">
                                        <div class="search-box">
                                            <input type="text" class="form-control form-control-sm" id="addDetailsSearch" placeholder="搜索试剂...">
                                        </div>
                                        <div class="options-container" id="addDetailsOptions">
                                            <div class="text-muted text-center py-3">
                                                <i class="bi bi-hourglass-split"></i> 正在加载试剂列表...
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i>取消
                    </button>
                    <button type="button" class="btn btn-success" onclick="saveData()">
                        <i class="bi bi-check-circle me-1"></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel"><i class="bi bi-pencil-square me-2"></i>编辑使用记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body2">
                    <form id="editForm">
                        <input type="hidden" id="editId">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="editTime" class="form-label">使用时间</label>
                                <input type="datetime-local" class="form-control" id="editTime" disabled>
                            </div>
                            <div class="col-md-6">
                                <label for="editExperimentId" class="form-label">实验号</label>
                                <input type="text" class="form-control" id="editExperimentId" disabled>
                            </div>
                            <div class="col-12">
                                <label for="editGroups" class="form-label">分组</label>
                                <div class="row" id="editGroups">
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="乳腺" id="editGroup1">
                                            <label class="form-check-label" for="editGroup1">乳腺</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="前列腺" id="editGroup2">
                                            <label class="form-check-label" for="editGroup2">前列腺</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="宫颈" id="editGroup3">
                                            <label class="form-check-label" for="editGroup3">宫颈</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="宫内膜" id="editGroup4">
                                            <label class="form-check-label" for="editGroup4">宫内膜</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="神经内分" id="editGroup5">
                                            <label class="form-check-label" for="editGroup5">神经内分</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="甲状腺" id="editGroup6">
                                            <label class="form-check-label" for="editGroup6">甲状腺</label>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="细胞蜡块" id="editGroup7">
                                            <label class="form-check-label" for="editGroup7">细胞蜡块</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <label for="editDetails" class="form-label">详细项目</label>
                                <div class="multi-select-container">
                                    <div class="multi-select-input" id="editDetailsInput">
                                        <div class="selected-items" id="editSelectedItems">
                                            <span class="placeholder">请选择详细项目...</span>
                                        </div>
                                        <div class="dropdown-arrow">
                                            <i class="bi bi-chevron-down"></i>
                                        </div>
                                    </div>
                                    <div class="multi-select-dropdown" id="editDetailsDropdown" style="display: none;">
                                        <div class="search-box">
                                            <input type="text" class="form-control form-control-sm" id="editDetailsSearch" placeholder="搜索试剂...">
                                        </div>
                                        <div class="options-container" id="editDetailsOptions">
                                            <div class="text-muted text-center py-3">
                                                <i class="bi bi-hourglass-split"></i> 正在加载试剂列表...
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i>取消
                    </button>
                    <button type="button" class="btn btn-primary" onclick="updateData()">
                        <i class="bi bi-check-circle me-1"></i>更新
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 导入模态框 -->
    <div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="importModalLabel"><i class="bi bi-upload me-2"></i>导入数据</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <div class="file-upload-area">
                        <div class="file-upload-icon">
                            <i class="bi bi-cloud-upload"></i>
                        </div>
                        <h6 class="mb-3">选择Excel文件上传</h6>
                        <input type="file" class="form-control" id="importFile" accept=".xlsx,.xls">
                        <div class="mt-3">
                            <small class="text-muted">
                                支持 .xlsx 和 .xls 格式文件<br>
                                <a href="templates/excel_template_guide.html" target="_blank" class="text-decoration-none">
                                    <i class="bi bi-info-circle me-1"></i>查看Excel模板格式说明
                                </a>
                            </small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i>取消
                    </button>
                    <button type="button" class="btn btn-primary" onclick="importData()">
                        <i class="bi bi-upload me-1"></i>导入
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS -->
    <script src="js/bootstrap.bundle.min.js"></script>
    <!-- 自定义JavaScript -->
    <script src="js/common.js"></script>
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;
        let reagentList = []; // 存储page1的试剂数据

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadReagentList();
            loadData();
            
            // 点击外部区域关闭下拉框
            document.addEventListener('click', function() {
                closeAllDropdowns();
            });
        });

        // 加载数据
        function loadData(page = 1) {
            currentPage = page;
            
            // 搜索功能暂时注释
            /*
            const searchTime = document.getElementById('searchTime').value.trim();
            const searchExperimentId = document.getElementById('searchExperimentId').value.trim();
            const searchGroups = document.getElementById('searchGroups').value.trim();
            */
            
            const params = {
                page: 'page2',
                pageNum: page,
                pageSize: pageSize
            };
            
            // 搜索参数暂时注释
            /*
            const searchTime = document.getElementById('searchTime').value.trim();
            const searchExperimentId = document.getElementById('searchExperimentId').value.trim();
            const searchGroups = document.getElementById('searchGroups').value.trim();
            if (searchTime) params.use_time = searchTime;
            if (searchExperimentId) params.material_code = searchExperimentId;
            if (searchGroups) params.group_names = searchGroups;
            */
            
            Http.get('/api/data', params)
                .then(data => {
                    if (data.success) {
                        displayData(data.data);
                        updatePagination(data.pagination);
                    } else {
                        showAlert('error', '加载数据失败: ' + data.message);
                    }
                })
                .catch(error => {
                    showAlert('error', '网络错误: ' + error.message);
                });
        }

        // 显示数据
        function displayData(data) {
            const tbody = document.getElementById('dataTableBody');
            tbody.innerHTML = '';
            
            data.forEach((item, index) => {
                const startIndex = (currentPage - 1) * pageSize;
                const row = `
                    <tr class="fade-in">
                        <td>${startIndex + index + 1}</td>
                        <td>${item.use_time || '-'}</td>
                        <td>${item.material_code || '-'}</td>
                        <td>${item.group_names || '-'}</td>
                        <td title="${item.details || '-'}">${item.details ? item.details.split(',').join(', ') : '-'}</td>
                        <td class="action-buttons-cell">
                            <a href="javascript:void(0)" class="btn-text btn-edit" onclick="editData(${item.id})">编辑</a>
                            <a href="javascript:void(0)" class="btn-text btn-delete" onclick="deleteData(${item.id})">删除</a>
                        </td>
                    </tr>
                `;
                tbody.innerHTML += row;
            });
        }

        // 更新分页
        function updatePagination(pagination) {
            totalPages = pagination.totalPages;
            const paginationElement = document.getElementById('pagination');
            const paginationInfo = document.getElementById('paginationInfo');
            
            // 更新信息
            const startRecord = (currentPage - 1) * pageSize + 1;
            const endRecord = Math.min(currentPage * pageSize, pagination.total);
            paginationInfo.textContent = `显示 ${startRecord}-${endRecord} 条，共 ${pagination.total} 条记录`;
            
            // 生成分页按钮
            let paginationHTML = '';
            
            // 上一页
            // if (currentPage > 1) {
            //     paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="loadData(${currentPage - 1})"><i class="bi bi-chevron-left"></i></a></li>`;
            // } else {
            //     paginationHTML += `<li class="page-item disabled"><span class="page-link"><i class="bi bi-chevron-left"></i></span></li>`;
            // }
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    paginationHTML += `<li class="page-item active"><span class="page-link">${i}</span></li>`;
                } else {
                    paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="loadData(${i})">${i}</a></li>`;
                }
            }
            
            // 下一页
            // if (currentPage < totalPages) {
            //     paginationHTML += `<li class="page-item"><a class="page-link" href="javascript:void(0)" onclick="loadData(${currentPage + 1})"><i class="bi bi-chevron-right"></i></a></li>`;
            // } else {
            //     paginationHTML += `<li class="page-item disabled"><span class="page-link"><i class="bi bi-chevron-right"></i></span></li>`;
            // }
            
            paginationElement.innerHTML = paginationHTML;
        }

        // 加载试剂列表
        async function loadReagentList() {
            try {
                // 获取当前用户的所有page1试剂数据
                let allReagents = [];
                let currentPageNum = 1;
                let hasMore = true;
                
                while (hasMore) {
                    const result = await Http.get('/api/data', {
                        page: 'page1',
                        pageNum: currentPageNum,
                        pageSize: 100
                    });
                    
                    if (result.success) {
                        allReagents = allReagents.concat(result.data);
                        hasMore = currentPageNum < result.pagination.totalPages;
                        currentPageNum++;
                    } else {
                        hasMore = false;
                    }
                }
                
                reagentList = allReagents;
                // 初始化多选下拉框
                initializeDetailsDropdown();
                
            } catch (error) {
                console.error('加载试剂列表失败:', error);
                showAlert('error', '加载试剂列表失败: ' + error.message);
            }
        }

        // 初始化详细项目多选下拉框
        function initializeDetailsDropdown() {
            const addContainer = document.getElementById('addDetailsOptions');
            const editContainer = document.getElementById('editDetailsOptions');
            
            if (!reagentList || reagentList.length === 0) {
                addContainer.innerHTML = '<div class="no-options"><i class="bi bi-exclamation-triangle"></i> 暂无试剂数据</div>';
                editContainer.innerHTML = '<div class="no-options"><i class="bi bi-exclamation-triangle"></i> 暂无试剂数据</div>';
                return;
            }
            
            // 生成新增选项
            let addOptionsHTML = '';
            reagentList.forEach((reagent, index) => {
                const displayName = reagent.material_name;
                addOptionsHTML += `
                    <div class="option-item" data-value="${displayName}">
                        <input type="checkbox" id="addOption${index}" value="${displayName}">
                        <label for="addOption${index}">${displayName}</label>
                    </div>
                `;
            });
            addContainer.innerHTML = addOptionsHTML;
            
            // 生成编辑选项
            let editOptionsHTML = '';
            reagentList.forEach((reagent, index) => {
                const displayName = reagent.material_name;
                editOptionsHTML += `
                    <div class="option-item" data-value="${displayName}">
                        <input type="checkbox" id="editOption${index}" value="${displayName}">
                        <label for="editOption${index}">${displayName}</label>
                    </div>
                `;
            });
            editContainer.innerHTML = editOptionsHTML;
            
            // 初始化事件监听
            initializeMultiSelectEvents('add');
            initializeMultiSelectEvents('edit');
        }

        // 初始化多选下拉框事件
        function initializeMultiSelectEvents(prefix) {
            const input = document.getElementById(`${prefix}DetailsInput`);
            const dropdown = document.getElementById(`${prefix}DetailsDropdown`);
            const searchBox = document.getElementById(`${prefix}DetailsSearch`);
            const optionsContainer = document.getElementById(`${prefix}DetailsOptions`);
            const arrow = input.querySelector('.dropdown-arrow');
            
            // 点击输入框切换下拉框显示
            input.addEventListener('click', function(e) {
                e.stopPropagation();
                const isVisible = dropdown.style.display !== 'none';
                closeAllDropdowns();
                if (!isVisible) {
                    dropdown.style.display = 'block';
                    input.classList.add('active');
                    arrow.classList.add('rotated');
                    searchBox.focus();
                }
            });
            
            // 搜索功能
            searchBox.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                const options = optionsContainer.querySelectorAll('.option-item');
                
                options.forEach(option => {
                    const text = option.textContent.toLowerCase();
                    if (text.includes(searchTerm)) {
                        option.style.display = 'flex';
                    } else {
                        option.style.display = 'none';
                    }
                });
            });
            
            // 选项点击事件
            optionsContainer.addEventListener('click', function(e) {
                const optionItem = e.target.closest('.option-item');
                if (optionItem) {
                    const checkbox = optionItem.querySelector('input[type="checkbox"]');
                    if (e.target !== checkbox) {
                        checkbox.checked = !checkbox.checked;
                    }
                    updateSelectedItems(prefix);
                    e.stopPropagation();
                }
            });
            
            // 复选框变化事件
            optionsContainer.addEventListener('change', function(e) {
                if (e.target.type === 'checkbox') {
                    updateSelectedItems(prefix);
                }
            });
        }
        
        // 关闭所有下拉框
        function closeAllDropdowns() {
            document.querySelectorAll('.multi-select-dropdown').forEach(dropdown => {
                dropdown.style.display = 'none';
            });
            document.querySelectorAll('.multi-select-input').forEach(input => {
                input.classList.remove('active');
            });
            document.querySelectorAll('.dropdown-arrow').forEach(arrow => {
                arrow.classList.remove('rotated');
            });
        }
        
        // 更新选中项目显示
        function updateSelectedItems(prefix) {
            const selectedItemsContainer = document.getElementById(`${prefix}SelectedItems`);
            const checkboxes = document.querySelectorAll(`#${prefix}DetailsOptions input[type="checkbox"]:checked`);
            const optionItems = document.querySelectorAll(`#${prefix}DetailsOptions .option-item`);
            
            // 更新选项样式
            optionItems.forEach(item => {
                const checkbox = item.querySelector('input[type="checkbox"]');
                if (checkbox.checked) {
                    item.classList.add('selected');
                } else {
                    item.classList.remove('selected');
                }
            });
            
            if (checkboxes.length === 0) {
                selectedItemsContainer.innerHTML = '<span class="placeholder">请选择详细项目...</span>';
            } else {
                let selectedHTML = '';
                checkboxes.forEach(checkbox => {
                    selectedHTML += `
                        <span class="selected-item">
                            ${checkbox.value}
                            <span class="remove-btn" onclick="removeSelectedItem('${prefix}', '${checkbox.value}')">&times;</span>
                        </span>
                    `;
                });
                selectedItemsContainer.innerHTML = selectedHTML;
            }
        }
        
        // 移除选中项目
        function removeSelectedItem(prefix, value) {
            const checkbox = document.querySelector(`#${prefix}DetailsOptions input[value="${value}"]`);
            if (checkbox) {
                checkbox.checked = false;
                updateSelectedItems(prefix);
            }
        }
        
        // 获取选中的详细项目
        function getSelectedDetails(prefix) {
            const checkboxes = document.querySelectorAll(`#${prefix}DetailsOptions input[type="checkbox"]:checked`);
            return Array.from(checkboxes).map(cb => cb.value).join(',');
        }

        // 设置选中的详细项目
        function setSelectedDetails(prefix, details) {
            // 先清除所有选择
            document.querySelectorAll(`#${prefix}DetailsOptions input[type="checkbox"]`).forEach(cb => cb.checked = false);
            
            if (details) {
                const detailArray = details.split(',');
                detailArray.forEach(detail => {
                    const checkbox = document.querySelector(`#${prefix}DetailsOptions input[value="${detail.trim()}"]`);
                    if (checkbox) checkbox.checked = true;
                });
            }
            updateSelectedItems(prefix);
        }

        // 获取选中的分组
        function getSelectedGroups(prefix) {
            const checkboxes = document.querySelectorAll(`#${prefix}Groups input[type="checkbox"]:checked`);
            return Array.from(checkboxes).map(cb => cb.value).join(',');
        }

        // 设置选中的分组
        function setSelectedGroups(prefix, groups) {
            // 先清除所有选择
            document.querySelectorAll(`#${prefix}Groups input[type="checkbox"]`).forEach(cb => cb.checked = false);
            
            if (groups) {
                const groupArray = groups.split(',');
                groupArray.forEach(group => {
                    const checkbox = document.querySelector(`#${prefix}Groups input[value="${group.trim()}"]`);
                    if (checkbox) checkbox.checked = true;
                });
            }
        }

        // 搜索数据 - 暂时注释
        /*
        function searchData() {
            loadData(1);
        }
        */

        // 保存数据
        function saveData() {
            // 表单验证
            const useTime = document.getElementById('addTime').value.trim();
            const materialCode = document.getElementById('addExperimentId').value.trim();
            const groupNames = getSelectedGroups('add');
            const details = getSelectedDetails('add');
            
            // 必填字段验证
            if (!useTime) {
                showAlert('warning', '请选择使用时间');
                return;
            }
            if (!materialCode) {
                showAlert('warning', '请填写实验号');
                return;
            }
            if (!groupNames) {
                showAlert('warning', '请选择分组');
                return;
            }
            if (!details) {
                showAlert('warning', '请选择详细项目');
                return;
            }
            
            // 字段长度验证
            // if (materialCode.length > 50) {
            //     showAlert('warning', '实验号不能超过50个字符');
            //     return;
            // }
            // if (details.length > 1000) {
            //     showAlert('warning', '详细项目选择过多，请适当减少');
            //     return;
            // }
            
            // 特殊字符验证
            const specialChars = /[<>'"&]/;
            if (specialChars.test(materialCode)) {
                showAlert('warning', '实验号不能包含特殊字符 < > \' " &');
                return;
            }

            const data = {
                use_time: useTime,
                material_code: materialCode,
                group_names: groupNames,
                details: details
            };

            Http.post('/api/data?page=page2', data)
            .then(result => {
                if (result.success) {
                    showAlert('success', '数据保存成功');
                    bootstrap.Modal.getInstance(document.getElementById('addModal')).hide();
                    document.getElementById('addForm').reset();
                    setSelectedGroups('add', '');
                    setSelectedDetails('add', '');
                    loadData(currentPage);
                } else {
                    showAlert('error', '保存失败: ' + result.message);
                }
            })
            .catch(error => {
                showAlert('error', '网络错误: ' + error.message);
            });
        }

        // 编辑数据
        function editData(id) {
            Http.get('/api/data', {page: 'page2', id: id})
                .then(data => {
                    if (data.success && data.data.length > 0) {
                        const item = data.data[0];
                        document.getElementById('editId').value = item.id;
                        document.getElementById('editTime').value = item.use_time || '';
                        document.getElementById('editExperimentId').value = item.material_code || '';
                        setSelectedGroups('edit', item.group_names || '');
                        setSelectedDetails('edit', item.details || '');
                        
                        const editModal = new bootstrap.Modal(document.getElementById('editModal'));
                        editModal.show();
                    } else {
                        showAlert('error', '获取数据失败');
                    }
                })
                .catch(error => {
                    showAlert('error', '网络错误: ' + error.message);
                });
        }

        // 更新数据
        function updateData() {
            const id = document.getElementById('editId').value;
            
            // 表单验证
            const groupNames = getSelectedGroups('edit');
            const details = getSelectedDetails('edit');
            
            // 必填字段验证
            if (!groupNames) {
                showAlert('warning', '请选择分组');
                return;
            }
            if (!details) {
                showAlert('warning', '请选择详细项目');
                return;
            }
            
            // 字段长度验证
            if (details.length > 1000) {
                showAlert('warning', '详细项目选择过多，请适当减少');
                return;
            }
            
            const data = {
                group_names: groupNames,
                details: details
            };

            Http.put(`/api/data?page=page2&id=${id}`, data)
            .then(result => {
                if (result.success) {
                    showAlert('success', '数据更新成功');
                    bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
                    loadData(currentPage);
                } else {
                    showAlert('error', '更新失败: ' + result.message);
                }
            })
            .catch(error => {
                showAlert('error', '网络错误: ' + error.message);
            });
        }

        // 删除数据
        function deleteData(id) {
            if (confirm('确定要删除这条记录吗？')) {
                Http.delete(`/api/data?page=page2&id=${id}`)
                .then(result => {
                    if (result.success) {
                        showAlert('success', '删除成功');
                        loadData(currentPage);
                    } else {
                        showAlert('error', '删除失败: ' + result.message);
                    }
                })
                .catch(error => {
                    showAlert('error', '网络错误: ' + error.message);
                });
            }
        }

        // 导入数据
        function importData() {
            const fileInput = document.getElementById('importFile');
            const file = fileInput.files[0];
            
            if (!file) {
                showAlert('warning', '请选择要导入的文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            // 获取当前用户（只通过URL参数传递，不在FormData中重复添加）
            const currentUser = Auth.getCurrentUser();
            
            const importBtn = document.querySelector('#importModal .btn-primary');
            const originalText = importBtn.innerHTML;
            importBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>导入中...';
            importBtn.disabled = true;
            
            fetch(`/api/upload-excel?page=page2&user_id=${encodeURIComponent(currentUser)}`, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showAlert('success', `导入成功！成功导入 ${result.data.success} 条记录`);
                    bootstrap.Modal.getInstance(document.getElementById('importModal')).hide();
                    fileInput.value = '';
                    loadData(currentPage);
                } else {
                    showAlert('error', '导入失败: ' + result.message);
                }
            })
            .catch(error => {
                showAlert('error', '网络错误: ' + error.message);
            })
            .finally(() => {
                importBtn.innerHTML = originalText;
                importBtn.disabled = false;
            });
        }

        // 显示提示信息
        function showAlert(type, message) {
            // 创建 toast 提示
            const toastContainer = document.getElementById('toastContainer') || createToastContainer();
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type === 'error' ? 'danger' : type === 'warning' ? 'warning' : 'success'} border-0`;
            toast.setAttribute('role', 'alert');
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bi bi-${type === 'error' ? 'exclamation-triangle' : type === 'warning' ? 'exclamation-circle' : 'check-circle'} me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast);
            bsToast.show();
            
            // 自动移除
            toast.addEventListener('hidden.bs.toast', () => {
                toast.remove();
            });
        }

        // 创建 toast 容器
        function createToastContainer() {
            const container = document.createElement('div');
            container.id = 'toastContainer';
            container.className = 'toast-container position-fixed top-0 end-0 p-3';
            container.style.zIndex = '9999';
            document.body.appendChild(container);
            return container;
        }
        
        // 初始化用户信息
        function initUserInfo() {
            const currentUser = Auth.getCurrentUser();
            if (currentUser) {
                document.getElementById('currentUserName').textContent = currentUser;
            }
        }
        
        // 添加退出登录事件
        document.getElementById('logoutBtn').addEventListener('click', function(e) {
            e.preventDefault();
            Auth.logout();
        });
        
        // 页面加载完成后初始化用户信息
        document.addEventListener('DOMContentLoaded', function() {
            initUserInfo();
        });
    </script>
</body>
</html>